package org.itboys.ace.web;

import org.itboys.admin.constant.AdminSessionConstant;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.itboys.seller.constant.SellerConstants;
import org.itboys.seller.dto.SellerGetMoneyDTO;
import org.itboys.seller.entity.SellerBank;
import org.itboys.seller.entity.SellerGetMoneyRecord;
import org.itboys.seller.service.SellerBankService;
import org.itboys.seller.service.SellerGetMoneyService;
import org.itboys.trade.entity.mysql.AdminAmount;
import org.itboys.trade.entity.mysql.AdminAmountRecord;
import org.itboys.trade.service.mysql.AdminAmountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by liangchong on 2016/6/13.
 */
@RestController
@RequestMapping("/seller/bank")
public class SellerBankController {

    @Autowired
    private SellerBankService sellerBankService;
    @Autowired
    private SellerGetMoneyService sellerGetMoneyService;
    @Autowired
    private AdminAmountService adminAmountService;

    @RequestMapping("/toListVM")
    public ModelAndView toListVM(HttpServletRequest request, HttpServletResponse response,Model model) {
        return new ModelAndView("/seller/seller-bank");
    }

    @RequestMapping("/toGetMoneyListVM")
    public ModelAndView toGetMoneyListVM(HttpServletRequest request, HttpServletResponse response,Model model) {
        long sellerId = (Long) ServletContextHolder.getSession().getAttribute(AdminSessionConstant.SHOP_ID);
        AdminAmount adminAmount = adminAmountService.getByUserIdAndType(sellerId, AdminAmountRecord.objType_seller);
        if (adminAmount != null) {
            model.addAttribute("validMoney",
                    new BigDecimal(adminAmount.getLeftWithdrawAmount()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN).floatValue());
        } else {
            model.addAttribute("validMoney", 0);
        }
        return new ModelAndView("/seller/seller-getmoney-list");
    }

    @ResponseBody
    @RequestMapping("/list")
    public void list(HttpServletRequest request,HttpServletResponse response){
        Page<SellerBank> page = sellerBankService.pageQuery(request);
        JsonPageUtils.renderJsonPage(page.getTotal(),page.getTotalPages(), page.getData(), response);
    }

    @ResponseBody
    @RequestMapping("/getMoneyList")
    public void getMoneyList(HttpServletRequest request,HttpServletResponse response){
        Page<SellerGetMoneyRecord> page = sellerGetMoneyService.pageQuery(request);
        List<SellerGetMoneyRecord> recordList = page.getData();
        List<SellerGetMoneyDTO> dtoList = recordList.stream().map(record -> {
            SellerGetMoneyDTO dto = new SellerGetMoneyDTO();
            SellerBank bank = sellerBankService.getById(record.getBankCardId());
            dto.setCardNum(bank.getCard());
            dto.setMoney(record.getMoney() / 100.0f);
            String statusStr = "";
            switch (record.getStatus()) {
                case SellerConstants.SellerGetMoneyStatus.UN_CHECK:
                    statusStr = "未审核";
                    break;
                case SellerConstants.SellerGetMoneyStatus.PASS:
                    statusStr = "已发放";
                    break;
                case SellerConstants.SellerGetMoneyStatus.REFUSE:
                    statusStr = "拒绝";
                    break;
                default:
                    statusStr = "未知";
            }
            dto.setStatus(statusStr);
            dto.setCommitIime(TimeUtils.format(new Date(record.getCt()), CommonConstants.DATE.FORMAT_DEFAULT));
            dto.setAuditTime(TimeUtils.format(new Date(record.getUt()), CommonConstants.DATE.FORMAT_DEFAULT));
            return dto;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(page.getTotal(),page.getTotalPages(), dtoList, response);
    }

    @ResponseBody
    @RequestMapping("/getBankInfo/{id}")
    public void getOrg(@PathVariable("id")Long id,HttpServletResponse response){
        AjaxUtils.renderJson(response, sellerBankService.getById(id));
    }

    @ResponseBody
    @RequestMapping("/save")
    public void save(@ModelAttribute SellerBank bank , HttpServletResponse response){
        try {
            if(bank.getId() == 0l){
                sellerBankService.save(bank);
            }else {
                sellerBankService.update(bank);
            }
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    @ResponseBody
    @RequestMapping("/saveGetMoneyInfo")
    public void saveGetMoneyInfo(@ModelAttribute SellerGetMoneyRecord bank , HttpServletResponse response){
        try {
            if (bank.getMoney() > 1000 * 100) {
                AjaxUtils.renderText(response, CommonConstants.FAIL);
                return;
            }
            if(bank.getId() == 0l){
                bank.setStatus(SellerConstants.SellerGetMoneyStatus.UN_CHECK);
                sellerGetMoneyService.save(bank);
            }else {
                sellerGetMoneyService.update(bank);
            }
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    @ResponseBody
    @RequestMapping("/delete/{id}")
    public void delete(@PathVariable("id")Long id,HttpServletResponse response){
        try {
            sellerBankService.delete(id);
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    @RequestMapping("/findAllBank")
    public void findAllBank(HttpServletRequest request , HttpServletResponse response) {
        Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
        List<SellerBank> banks = sellerBankService.list(param);
        List<SellerBank> dtos = banks.stream().map(s -> {
            s.setBankName(s.getBankName() + " " + s.getBranchBank());
            return s;
        }).collect(Collectors.toList());
        AjaxUtils.renderJson(response, dtos);
    }
}
